# from django.http import HttpResponse
# from django.conf import settings
# from django.views.decorators.csrf import csrf_exempt
# import os
# import uuid
# import json
# import datetime as dt
#
#
# @csrf_exempt
# def upload_image(request, dir_name):
#     result = {'error': 1, 'message': '上传出错'}
#     files = request.FILES.get('imgFile', None)
#     if files:
#         result = image_upload(files, dir_name)
#     return HttpResponse(json.dumps(result),
#                         content_type='application/json')
#
#
# # 目录创建
# def upload_generation_dir(dir_name):
#     # print dir_name, '----dir_name'
#     today = dt.datetime.today()
#     dir_name = dir_name + '/%d/%d/' % (today.year, today.month)
#     if not os.path.exists(settings.MEDIA_ROOT + dir_name):
#         os.makedirs(settings.MEDIA_ROOT + dir_name)
#
# # 图片上传
# def image_upload(files, dir_name):
#     # 允许上传的类型
#     allow_suffix = ['jpg', 'png', 'jpeg', 'git', 'bmp']
#     file_suffix = files.name.split('.')[-1]
#     if file_suffix not in allow_suffix:
#         return {'error': 1, 'message': '图片格式不正确'}
#     relative_path_file = upload_generation_dir(dir_name)
#     # print relative_path_file, '-----relative_path_file'
#     path = os.path.join(settings.MEDIA_ROOT, relative_path_file)
#     # print path, '----------path'
#     if not os.path.exists(path):
#         os.makedirs(path)
#     file_name = str(uuid.uuid1()) + '.' + file_suffix
#     path_file = os.path.join(path, file_name)
#     file_url = settings.MEDIA_URL + relative_path_file + file_name
#     open(path_file, 'wb').write(files.file.read())
#     return {'error': 0, 'url': file_url}
from ckeditor_uploader import image_processing,utils
from django.conf import settings
from django.http import HttpResponse
from django.http import JsonResponse
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from django.utils.html import escape


class ImageUploadView(APIView):
    permission_classes = [IsAuthenticated]
    http_method_names = ['post']

    def post(self, request, **kwargs):
        """
        Uploads a file and send back its URL to CKEditor.
        """
        uploaded_file = request.FILES['upload']

        backend = image_processing.get_backend()

        ck_func_num = request.GET.get('CKEditorFuncNum')
        if ck_func_num:
            ck_func_num = escape(ck_func_num)

        # Throws an error when an non-image file are uploaded.
        if not getattr(settings, 'CKEDITOR_ALLOW_NONIMAGE_FILES', True):
            try:
                backend.image_verify(uploaded_file)
            except utils.NotAnImageException:
                return HttpResponse("""
                    <script type='text/javascript'>
                    window.parent.CKEDITOR.tools.callFunction({0}, '', 'Invalid file type.');
                    </script>""".format(ck_func_num))

        saved_path = self._save_file(request, uploaded_file)
        if len(str(saved_path).split('.')) > 1:
            if(str(saved_path).split('.')[1].lower() != 'gif'):
                self._create_thumbnail_if_needed(backend, saved_path)
        url = utils.get_media_url(saved_path)

        if ck_func_num:
            # Respond with Javascript sending ckeditor upload url.
            return HttpResponse("""
            <script type='text/javascript'>
                window.parent.CKEDITOR.tools.callFunction({0}, '{1}');
            </script>""".format(ck_func_num, url))
        else:
            retdata = {'url': url, 'uploaded': '1',
                       'fileName': uploaded_file.name}
            return JsonResponse(retdata)
